package com.yuan.weike.service.impl;

import com.yuan.weike.mapper.TaskMapper;
import com.yuan.weike.model.Task;
import com.yuan.weike.model.TaskStatusEnum;
import com.yuan.weike.model.TaskWithEmployer;
import com.yuan.weike.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Override
    public Task publishTask(Task task) {
        // 设置任务状态为待承接
        task.setStatus(TaskStatusEnum.PENDING.getCode());
        // 设置发布时间
        task.setPublishDate(new Date());
        // 设置创建和更新时间
        task.setCreatedTime(new Date());
        task.setUpdatedTime(new Date());
        
        // 插入任务
        taskMapper.insert(task);
        return task;
    }

    @Override
    public Task getTaskById(Long taskId) {
        return taskMapper.selectById(taskId);
    }

    @Override
    public TaskWithEmployer getTaskByIdWithEmployer(Long taskId) {
        return taskMapper.selectByIdWithEmployer(taskId);
    }

    @Override
    /**
     * 获取所有未关闭的任务（状态不等于3）
     */
    public List<Task> getAllTasks() {
        return taskMapper.selectAll();
    }

    @Override
    public List<TaskWithEmployer> getAllTasksWithEmployer() {
        return taskMapper.selectAllWithEmployer();
    }

    @Override
    public List<TaskWithEmployer> getAllTasksWithEmployerIncludeClosed() {
        return taskMapper.selectAllWithEmployerIncludeClosed();
    }

    @Override
    public List<Task> getTasksByEmployerId(Long employerId) {
        return taskMapper.selectByEmployerId(employerId);
    }

    @Override
    public List<TaskWithEmployer> getTasksByEmployeeId(Long employeeId) {
        return taskMapper.selectByEmployeeId(employeeId);
    }

    @Override
    public List<TaskWithEmployer> getTasksByIds(List<Long> taskIds) {
        if (taskIds == null || taskIds.isEmpty()) {
            return List.of();
        }
        return taskMapper.selectByIds(taskIds);
    }

    @Override
    public Task updateTask(Task task) {
        task.setUpdatedTime(new Date());
        taskMapper.update(task);
        return task;
    }

    @Override
    public boolean deleteTask(Long taskId) {
        return taskMapper.deleteById(taskId) > 0;
    }
    
    @Override
    public Task closeTask(Long taskId) {
        Task task = taskMapper.selectById(taskId);
        if (task != null) {
            task.setStatus(TaskStatusEnum.CLOSED.getCode());
            task.setUpdatedTime(new Date());
            taskMapper.update(task);
        }
        return task;
    }
    
    @Override
    public int countTasks() {
        return taskMapper.countAll();
    }
}